package com.gr.jron.webapp;

import org.acegisecurity.captcha.CaptchaServiceProxy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.ImageCaptchaService;

/**
 * Created by Jronrun.
 * User: jron
 * Date: 2007-11-3
 * Time: 13:24:06
 * It's jron's dream to cqiu
 * <p/>
 * Allows the SpringFramework acegi-security captcha package to access the the
 * JCAPTCHA service. Captcha validation results are logged.
 */
public class JCaptchaServiceProxyImpl implements CaptchaServiceProxy {
    protected static final Log log = LogFactory.getLog(JCaptchaServiceProxyImpl.class);
    private ImageCaptchaService jcaptchaService;

    public boolean validateReponseForId(String id, Object response) {
        log.debug("validating captcha response");
        try {
            boolean isHuman = jcaptchaService.validateResponseForID(id, response);
            if (isHuman) log.debug("captcha passed");
            else log.warn("captcha failed");
            return isHuman;
        } catch (CaptchaServiceException cse) {
            // fixes known bug in JCaptcha
            log.warn("captcha validation failed due to exception", cse);
            return false;
        }
    }

    public void setJcaptchaService(ImageCaptchaService jcaptchaService) {
        this.jcaptchaService = jcaptchaService;
    }
}